<template>
<div class="back-top" @click="backTop" ref="backTop">
    <span class="icon-shangjiantou"></span>
    <p>TOP</p>
</div>
</template>

<script>
export default {
  name: 'backTop',
  methods: {
 // 回到顶部动画
    backTop() {

      let obtn = this.$refs.backTop,
        //文档高度
        clientHeight = document.documentElement.clientHeight,
        time = null,
        isTop = true,
        cancelScroll = false;

      if (cancelScroll == false) {
        time = setInterval(function () {
          var osTop = document.documentElement.scrollTop || document.body.scrollTop;
          var ispeed = Math.floor(-osTop / 10);
          document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
          isTop = true;
          if (osTop === 0) {
            clearInterval(time);
          }
        }, 13);
      } else {
        clearInterval(time);
        cancelScroll = true;
      }
    }
  },
  mounted() {
    let obtn = this.$refs.backTop,
      timer,
      alpha = 0
    addEvent(window, 'scroll', function () {
      let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
      if (scrollTop < 400) {
        startchange(0)
      } else {
        startchange(100)
      }
    })
    // 透明动画函数
    function startchange(value) {
      clearInterval(timer)
      let speed = 0;

      if (value > alpha) {
        speed = 10;
      } else if (value < alpha) {
        speed = -10;
      }
      if (value === 100) {
        obtn.style.display = 'block';

      }
      timer = setInterval(function () {
        if (value === alpha) {
          clearInterval(timer)
        } else {
          alpha += speed;
          obtn.style.filter = 'alpha(opacity:' + alpha + ')'
          obtn.style.opacity = alpha / 100
          if (alpha === 0) {
            obtn.style.display = 'none'
          }
        }
      }, 10)
    }

    // 绑定事件兼容
    function addEvent(obj, type, eFn) {
      function fn(e, b) {
        e = e || window.event;
        eFn.call(obj, e)
      }
      if (window.addEventListener) {
        obj.addEventListener(type, fn, false)
      } else {
        obj.attachEvent('on' + type, fn)
      }
      return fn;
    }
  },
}
</script>

<style lang="stylus" scoped>
    .back-top{
        display: none;
        position: fixed;
        z-index: 100;
        right: 30px;
        bottom: 88px;
        width: 44px;
        height: 44px;
        padding-top: 6px;
        background-color: #000;
        font-size: 12px;
        color: #fff;
        text-align: center;
        cursor: pointer;
        &:hover{
            background-color: #1457FD;
        }
    }
</style>
